package config;

import java.io.File;
import java.io.FilenameFilter;

import org.apache.commons.lang3.StringUtils;

import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.template.Engine;
import com.system.SystemUserRoutes;
import com.system.model.SystemUser;

public class SystemConfig extends JFinalConfig {
	
	public static final String SYSTEM_CONFIG_PATH = "sysconfig.properties";

	@Override
	public void configConstant(Constants me) {
		PropKit.use(SYSTEM_CONFIG_PATH, "utf-8");
		me.setDevMode(PropKit.getBoolean("devMode"));
	}

	@Override
	public void configEngine(Engine me) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void configHandler(Handlers me) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void configInterceptor(Interceptors me) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void configPlugin(Plugins me) {
		Prop p = PropKit.use("jdbc.properties");
		DruidPlugin dp = new DruidPlugin(p.get("jdbc.url"), 
				p.get("jdbc.username"), 
				p.get("jdbc.password"), 
				p.get("jdbc.driverclass"));
		
//		dp.set(p.getInt("jdbc.poolsize.initial", 2), 
//				p.getInt("jdbc.idletime.max", 60), 
//				p.getInt("jdbc.poolsize.max", 40));
		me.add(dp);
		
		
		ActiveRecordPlugin arp = new ActiveRecordPlugin(dp);
		
		File sqlDir = new File(PathKit.getWebRootPath() + PropKit.get("sqlTemplateDir"));
		arp.setBaseSqlTemplatePath(sqlDir.getAbsolutePath());
		if(sqlDir.exists()){
			File[] sqls = sqlDir.listFiles(new FilenameFilter() {
				
				@Override
				public boolean accept(File dir, String name) {
					return name.endsWith(PropKit.get("sqlFileName"));
				}
			});
			for(File f : sqls){
				arp.addSqlTemplate(f.getName());
			}
		}
		
		arp.addMapping("systemUser", SystemUser.class);
		me.add(arp);
	}

	@Override
	public void configRoute(Routes me) {
		me.add(new SystemUserRoutes());
		
		String[] routes = PropKit.get("routesList", "").split(",");
		Class<?> cls;
		for(String route : routes){
			try {
				if(StringUtils.isNotEmpty(route)){
					cls = Class.forName(route);
					if(cls.isAssignableFrom(Routes.class)){
						me.add((Routes) cls.newInstance());
					}
				}
			} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
				throw new RuntimeException(e);
			}
		}
	}

}
